package com.example.wxsmart.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.wxsmart.config.WeiXinConfig;
import com.example.wxsmart.util.OkHttpUtil;
import com.example.wxsmart.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author Luojunxian
 * @data 2022/5/31 9:28
 * @classname WeiXinMessageResources
 */
@Slf4j
@Component
public class WeiXinMessageResources {

    public static final String ACCESS_TOKEN = "access_token";
    public static final Integer ACCESS_TOKEN_EXPIRE = 7200;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private WeiXinConfig weiXinConfig;

    /**
     * 对回复消息体进行拼接
     *
     * @param message 消息
     * @return {@code JSONObject}
     */
    private JSONObject getMessage(String message) {
        // 进行回复(针对群聊回复)
        JSONObject json = new JSONObject();
        json.put("touser", weiXinConfig.getTouser());
        json.put("msgtype", "text");
        json.put("agentid", weiXinConfig.getAgentId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", message);
        json.put("text", jsonObject);
        json.put("safe", 0);
        log.info("回复消息:{}", message);
        return json;
    }

    /**
     * 获取access_token(有效期7200秒,即两小时)
     *
     * @return {@code String}
     */
    public String accessToken() {
        String url = String.format("%s?corpid=%s&corpsecret=%s",
                weiXinConfig.getAccess_token_url(), weiXinConfig.getSCorpID(), weiXinConfig.getSecret());

        JSONObject result = JSON.parseObject(OkHttpUtil.sendGet(url));
        String accessToken = result.getString("access_token");
        log.info("access_token:{}", accessToken);
        return accessToken;
    }

    /**
     * 向企业微信应用发送消息
     *
     * @param message 消息
     * @return {@code String}
     */
    public String sendMessage(String message) {
        log.info("从redis中获取access_token...");
        String accessToken = (String) redisUtil.get(ACCESS_TOKEN);

        if (null == accessToken) {
            log.info("access_token已过期,重新获取token...");
            accessToken = accessToken();
            Optional.ofNullable(accessToken).orElseThrow(() -> new RuntimeException("微信获取access_token错误"));
            redisUtil.set(ACCESS_TOKEN, accessToken, ACCESS_TOKEN_EXPIRE);
        }

        String url = String.format("%s?access_token=%s", weiXinConfig.getSend_message_url(), accessToken);

        String sendPost = OkHttpUtil.sendPost(url, getMessage(message));

        log.info("sendPost返回:{}", sendPost);

        JSONObject jsonObject = JSON.parseObject(sendPost);

        // 如果返回的errcode不是0,即报错,则移除access_token,等下次重试
        if (!"0".equals(jsonObject.getString("errcode"))) {
            redisUtil.del(ACCESS_TOKEN);
        }

        return sendPost;
    }

    /**
     * es检索为空时,检索关键词的近似词语返回
     *
     * @param message 消息
     * @return {@code String}
     */
    public String getBaiDu(String message) {
        log.info("Baidu:开始查找【{}】近义词...", message);
        String url = String.format("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?" +
                "wd=%s&json=1", message);

        try {
            String sendGet = OkHttpUtil.sendGet(url);

            List<String> list = JSON.parseObject(sendGet.substring(17, sendGet.length() - 2))
                    .getObject("s", List.class);

            return "抱歉,未找到相关回答,你想问的大概是:\r\n" + String.join("\r\n", list);
        } catch (Exception e) {
            log.error("Baidu:查找错误,问题:{}", e.getMessage());
        }

        return "抱歉,未找到相关回答,还在努力学习中...";
    }
}
